package main

import (
	"context"
	"github.com/gin-gonic/gin"
	"github.com/opentracing/opentracing-go"
	"github.com/opentracing/opentracing-go/ext"
	zipkinot "github.com/openzipkin-contrib/zipkin-go-opentracing"
	"opentracing-study/common"
	"time"
)

func main() {
	// init zipkin
	trace, err := common.NewZipkin(common.ServerAppID, "172.16.0.1:8000")
	if err != nil {
		panic(err)
	}
	opentracing.SetGlobalTracer(zipkinot.Wrap(trace))
	route := gin.Default()
	route.Use(common.Trace())
	route.GET("/api/v1/user/info", func(ctx *gin.Context) {
		// get trace ctx
		var (
			trCtx context.Context
			ok    bool
		)
		if trCtx, ok = ctx.Value(common.TraceCtx).(context.Context); !ok {
			ctx.String(500, "没有找到上下文")
			return
		}
		// mock span
		span, trCtx := opentracing.StartSpanFromContext(trCtx, "db")
		defer span.Finish()
		ext.SpanKind.Set(span, "client")
		ext.Component.Set(span, "database/mysql")
		ext.DBType.Set(span, "mysql")
		ext.DBInstance.Set(span, "mysql://127.0.0.1:3306/test")
		ext.DBStatement.Set(span, "select username,password from user_table where username=?")
		time.Sleep(10 * time.Millisecond)
		ctx.JSON(200, gin.H{
			"code":    0,
			"message": "ok!",
			"data": gin.H{
				"username": "test",
				"password": "pass",
			},
		})
	})
	if err := route.Run("0.0.0.0:8000"); err != nil {
		panic(err)
	}
}
